const { google } = require('googleapis');
const androidpublisher = google.androidpublisher('v3');
const fs = require('fs');
const path = require('path');

async function uploadApkToInternalTrack(packageName, apkPath) {
    try {
        // 进行身份验证并获得API访问权限
        let auth = new google.auth.GoogleAuth({
            scopes: ['https://www.googleapis.com/auth/androidpublisher']
        });
        let authClient = await auth.getClient();
        google.options({ auth: authClient });

        // 启动一个编辑会话
        const appEdit = await androidpublisher.edits.insert({
            packageName: packageName,
        });
        let editId = appEdit.data.id;

        // 上传APK到编辑会话
        const apkResponse = await androidpublisher.edits.apks.upload({
            packageName: packageName,
            editId: editId,
            media: {
                mimeType: 'application/vnd.android.package-archive',
                body: fs.createReadStream(apkPath),
            },
        });
        const versionCode = apkResponse.data.versionCode;

        // 分配新的APK版本到内测轨道
        await androidpublisher.edits.tracks.update({
            packageName: packageName,
            editId: editId,
            track: 'internal',
            requestBody: {
                releases: [{
                    name: `Internal release ${versionCode}`, // 发布名称（可选）
                    versionCodes: [versionCode],
                    status: 'completed', // 或其他状态
                }],
            },
        });

        // 提交编辑会话
        await androidpublisher.edits.commit({
            packageName: packageName,
            editId: editId,
        });

        console.log(`APK ${versionCode} 成功上传到内测轨道`);
    } catch (error) {
        console.error('上传APK到内测轨道时出错:', error.message);
    }
}

// 调用函数
uploadApkToInternalTrack('com.example.app', path.join(__dirname, 'your.apk'));
